/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller.SRV;

import entity.MUser;
import entity.SrvCureplan;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import session.MUserFacade;
import session.SrvCureplanFacade;
import util.jQgrid.JQGridFormatterUtil;
import util.jQgrid.JQGridRow;

/**
 *
 * @author SUNTIPARB
 */
@WebServlet(name="SRV_MUserDetail",
                loadOnStartup = 1,
                urlPatterns={"/SRV/MUserDetail",
                            "/SRV/MUserDetail/formMUser_Submit",
                            "/SRV/MUserDetail/grd_search"})
public class SRV_MUserDetail extends HttpServlet {
    @EJB
    private MUserFacade mUserFacade;
    @EJB
    private SrvCureplanFacade srvCureplanFacade;
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String userPath = request.getServletPath();
        HttpSession session = request.getSession();

        // if category page is requested
        if (userPath.equals("/SRV/MUserDetail")) {
            //check redirect form CurePlanDetail
            String cureServiceId = (request.getParameter("cureServiceId") != null) ? request.getParameter("cureServiceId").trim() : "";
            String curePlanId = (request.getParameter("curePlanId") != null) ? request.getParameter("curePlanId").trim() : "";
            String fromPage = (request.getParameter("fromPage") != null) ? request.getParameter("fromPage").trim() : "";
            request.setAttribute("cureServiceId", cureServiceId);
            request.setAttribute("curePlanId", curePlanId);
            request.setAttribute("fromPage", fromPage);
            request.setAttribute("disabledInput", cureServiceId.equals("")?"":"Disabled");

            //response.setContentType("text/html;charset=utf-8");
            String UserId = request.getParameter("id");
            UserId = "1"; // fixed for prototype
            if (!UserId.equals("-1")){
                List<MUser> lMUser;
                try {
                    //Query Java Object
                    lMUser = mUserFacade.findByUserId(UserId);
                    if (!lMUser.isEmpty()) {
                        request.setAttribute("UserId", UserId);
                        request.setAttribute("hdd_UserId", UserId);
                        for (MUser obj : lMUser) {
                            request.setAttribute("txtUsername", obj.getUsername());
                            request.setAttribute("txtName", obj.getName());
                            request.setAttribute("txtSurname", obj.getSurname());
                            request.setAttribute("chcPerm_File", (obj.getPermFile())?"Checked":"");
                            request.setAttribute("chcPerm_Log", (obj.getPermLog())?"Checked":"");
                        }
                    }
                } catch (Exception ex) {
                    System.out.println("Error message" + ex.getMessage());
                } finally {
                    lMUser = null;
                }
            }else{
                request.getRequestDispatcher("home.jsp").forward(request, response);
            }

            userPath = "/SRV/MUserDetail";
        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as
        // 8-bit Unicode (e.g., for Czech characters)
        Boolean isDispatcher = true; //กำหนดว่า ต้องการให้เปลี่ยนหน้าหรือไม่ ? ต้องการ : ไม่ต้องการ
        String userPath = request.getServletPath();
        HttpSession session = request.getSession();


        if (userPath.equals("/SRV/MUserDetail/formMUser_Submit")) {
            response.setContentType("text/html;charset=utf-8");
            String UserId = (request.getParameter("UserId") != null) ? request.getParameter("UserId") : "-1";
            String txtUsername = (request.getParameter("txtUsername") != null) ? request.getParameter("txtUsername") : "";
            String txtName = (request.getParameter("txtName") != null) ? request.getParameter("txtName") : "";
            String txtSurname = (request.getParameter("txtSurname") != null) ? request.getParameter("txtSurname") : "";
            String chcPerm_File = (request.getParameter("chcPerm_File") != null) ? request.getParameter("chcPerm_File") : "false";
            String chcPerm_Log = (request.getParameter("chcPerm_Log") != null) ? request.getParameter("chcPerm_Log") : "false";

            PrintWriter out = response.getWriter();
            try {
                //Query Java Object
                if (!UserId.equals("-1")){
                    mUserFacade.EditUser(UserId, txtUsername, txtName, txtSurname, chcPerm_File, chcPerm_Log);
                }else{
                    //do nothing
                }
                String strHTML = "complete";
                out.println(strHTML);
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
            }

            isDispatcher = false;
        }

        if (userPath.equals("/SRV/MUserDetail/grd_search")) {
            response.setContentType("text/json;charset=utf-8");
            String qstr_page = request.getParameter("page"); // get the requested page
            String qstr_limit = request.getParameter("rows"); // get how many rows we want to have into the grid
            String qstr_sidx = request.getParameter("sidx"); // get index row - i.e. user click to sort
            String qstr_sord = request.getParameter("sord"); // get the direction

            if (qstr_sidx.isEmpty()) {
                qstr_sidx = "id";
                qstr_sord = "asc";
            }

            String txtKeyword = (request.getParameter("txtKeyword") != null) ? request.getParameter("txtKeyword") : "";
            String txtPrice = (request.getParameter("txtPrice") != null) ? request.getParameter("txtPrice") : "";
            String ddlStatus = (request.getParameter("ddlStatus") != null) ? request.getParameter("ddlStatus") : "";
            String UserId = (request.getParameter("UserId") != null) ? request.getParameter("UserId") : "";

            PrintWriter out = response.getWriter();
            List<SrvCureplan> lSrvCureplan;
            List rows;
            JQGridRow row;
            List cells;
            String strJson = "";
            int totalRecords = 0;
            int endList = Integer.parseInt(qstr_limit)*Integer.parseInt(qstr_page);
            int startList = Integer.parseInt(qstr_limit)*Integer.parseInt(qstr_page) - Integer.parseInt(qstr_limit);
            try {
                //Query Java Object
                lSrvCureplan = srvCureplanFacade.LoadDataCurePlanByUserId(UserId, txtKeyword, txtPrice, ddlStatus, qstr_sidx ,qstr_sord);
                totalRecords = lSrvCureplan.size();
                if (endList>totalRecords){
                    endList=totalRecords;
                }
                //Use List rows
                rows = new ArrayList();
                if (!lSrvCureplan.isEmpty()) {
                    for (SrvCureplan obj : lSrvCureplan.subList(startList, endList)) {
                        row = new JQGridRow();
                        row.setId(obj.getId());

                        cells = new ArrayList();
                        cells.add(obj.getId().toString());
                        cells.add(obj.getSrvCureservice().getName());
                        cells.add(obj.getSrvCureservice().getPrice().toString());
                        cells.add(obj.getSrvCureservice().getCurrency());
                        if (obj.getSrvCureservice().getMDoctor() != null) {
                            cells.add(obj.getSrvCureservice().getMDoctor().getName()+" "+obj.getSrvCureservice().getMDoctor().getSurname());
                        } else {
                            cells.add("");
                        }
                        if (obj.getSrvCureservice().getMHospital() != null) {
                            cells.add(obj.getSrvCureservice().getMHospital().getName());
                        } else {
                            cells.add("");
                        }
                        String strStatus = controller.enumConstant.StatusConstant.valueOf(obj.getStatus().toString()).getStatus();
                        cells.add(strStatus);

                        row.setCell(cells);
                        rows.add(row);
                    }
                }

                strJson = JQGridFormatterUtil.getJSON(Integer.parseInt(qstr_page), Integer.parseInt(qstr_limit), totalRecords, rows);
                out.println(strJson);
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
                lSrvCureplan = null;
                rows = null;
                row = null;
                cells = null;
                strJson = null;
            }

            isDispatcher = false;
        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            if (isDispatcher) {
                request.getRequestDispatcher(url).forward(request, response);
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }

    }
}
